<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我的游记</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: '微软雅黑', sans-serif;
            background-color: #f5f5f5;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        /* 发布按钮 */
        .create-btn {
            position: fixed;
            bottom: 40px;
            right: 40px;
            background: #4CAF50;
            color: white;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0,0,0,0.3);
            z-index: 100;
        }

        /* 发布表单弹窗 */
        .post-form {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 30px;
            border-radius: 8px;
            width: 80%;
            max-width: 600px;
            box-shadow: 0 0 20px rgba(0,0,0,0.2);
            z-index: 1000;
            display: none;
        }

        .form-group {
            margin-bottom: 20px;
        }

        input, textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .post-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 30px;
        }

        .post-card {
            background: white;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            transition: transform 0.3s;
            cursor: pointer;
        }

        .post-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        .post-cover {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 4px;
            margin-bottom: 10px;
        }

        .post-meta {
            display: flex;
            justify-content: space-between;
            color: #666;
            font-size: 0.9em;
            margin-top: 10px;
        }

        .image-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 8px;
            margin: 10px 0;
        }

        .post-img {
            width: 100%;
            height: 120px;
            object-fit: cover;
            border-radius: 4px;
        }

        .stats {
            display: flex;
            gap: 15px;
            color: #666;
        }

        .stat-item {
            display: flex;
            align-items: center;
        }

        .stat-item i {
            font-size: 16px;
            margin-right: 5px;
            color: #666;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .post-content {
            margin: 10px 0;
            line-height: 1.6;
            color: #333;
            max-height: 100px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .form-actions button {
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }

        .form-actions button[type="submit"] {
            background: #4CAF50;
            color: white;
            border: none;
        }

        .form-actions button[type="button"] {
            background: #f5f5f5;
            border: 1px solid #ddd;
        }

        .loading {
            text-align: center;
            padding: 20px;
            font-size: 18px;
            color: #666;
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
<div id="app">
    <div class="container">
        <h1>我的游记</h1>

        <div v-if="loading" class="loading">
            <i class="fas fa-spinner fa-spin"></i> 加载中...
        </div>

        <div v-else-if="notes.length === 0" class="empty-state">
            <i class="fas fa-book-open" style="font-size: 48px; margin-bottom: 15px;"></i>
            <p>您还没有发布过游记</p>
            <button @click="checkAuth" style="padding: 8px 16px; background: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">
                发布第一篇游记
            </button>
        </div>

        <div v-else class="post-list">
            <div class="post-card" v-for="note in notes" :key="note.nid" @click="goToDetail(note.nid)">
                <!-- 封面图片 -->
                <img v-if="note.img1"
                     :src="getImageUrl(note.img1)"
                     class="post-cover"
                     @error="handleCoverError"
                     alt="游记封面">
                <img v-else :src="defaultCover" class="post-cover" alt="默认封面">

                <!-- 标题和内容 -->
                <h3>{{ note.title }}</h3>
                <div class="post-content">{{ truncateContent(note.content) }}</div>

                <div class="post-meta">
                    <span>{{ formatDate(note.created_at) }}</span>
                    <div class="stats">
                        <div class="stat-item">
                            <i class="fas fa-eye"></i>{{ note.view_count || 0 }}
                        </div>
                        <div class="stat-item">
                            <i class="fas fa-heart"></i>{{ note.like_count || 0 }}
                        </div>
                        <div class="stat-item">
                            <i class="fas fa-comment"></i>{{ note.comment_count || 0 }}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 发布按钮 -->
    <div class="create-btn" @click="checkAuth">+</div>

    <!-- 发布表单 -->
    <div class="post-form" id="postForm">
        <h2>发布新游记</h2>
        <form @submit.prevent="submitPost">
            <div class="form-group">
                <input type="text" placeholder="游记标题" v-model="newNote.title" required>
            </div>
            <div class="form-group">
                <textarea placeholder="游记内容" rows="6" v-model="newNote.content" required></textarea>
            </div>
            <div class="form-group">
                <label>上传图片（最多3张）：</label>
                <input type="file"
                       v-for="n in 3"
                       :key="n"
                       :ref="'fileInput' + n"
                       @change="handleFileUpload(n-1)"
                       accept="image/*">
            </div>
            <div class="form-actions">
                <button type="button" @click="hideForm">取消</button>
                <button type="submit">发布</button>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@1.5.0/dist/axios.min.js"></script>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                isFormVisible: false,
                currentUser: JSON.parse(localStorage.getItem('userInfo')) || {},
                notes: [],
                loading: true,
                newNote: { title: '', content: '', images: [] },
                defaultCover: 'img/zw.png'
            };
        },
        created() {
            this.checkLoginStatus();
            this.fetchUserNotes();
        },
        methods: {
            // 检查登录状态
            checkLoginStatus() {
                if (!this.currentUser || !this.currentUser.uid) {
                    alert('请先登录！');
                    window.location.href = '/login.html'; // 跳转到登录页
                    return;
                }
            },

            // 获取用户帖子
            fetchUserNotes() {
                this.loading = true;
                axios.get('/index/notes', {
                    params: {
                        uid: this.currentUser.uid
                    }
                })
                    .then(response => {
                        this.loading = false;
                        if (response.data && response.data.code === 1) {
                            this.notes = response.data.data.list || [];
                        } else {
                            console.error('获取帖子失败:', response.data ? response.data.msg : '无返回数据');
                            this.notes = [];
                            alert('获取游记列表失败: ' + (response.data ? response.data.msg : '服务器错误'));
                        }
                    })
                    .catch(error => {
                        this.loading = false;
                        console.error('获取帖子出错:', error);
                        alert('获取游记列表失败，请检查网络连接');
                    });
            },

            // 安全转义HTML
            escapeHtml(unsafe) {
                if (!unsafe) return '';
                return unsafe
                    .replace(/&/g, "&amp;")
                    .replace(/</g, "&lt;")
                    .replace(/>/g, "&gt;")
                    .replace(/"/g, "&quot;")
                    .replace(/'/g, "&#039;");
            },

            getImageUrl(imgPath) {
                if (!imgPath) return this.defaultCover;

                // 如果已经是完整URL则直接返回
                if (imgPath.startsWith('http://') || imgPath.startsWith('https://')) {
                    return imgPath;
                }

                return imgPath.startsWith('/') ? imgPath : '/' + imgPath;
            },

            // 封面图片错误处理
            handleCoverError(event) {
                event.target.src = this.defaultCover;
                event.target.onerror = null;
            },

            // 格式化日期
            formatDate(dateString) {
                try {
                    const date = new Date(dateString);
                    return date.toLocaleDateString('en', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit'
                    });
                } catch {
                    return '未知时间';
                }
            },

            // 截断内容
            truncateContent(content, maxLength = 100) {
                if (!content) return '';
                return content.length > maxLength ?
                    content.substring(0, maxLength) + '...' : content;
            },

            // 跳转到详情页
            goToDetail(nid) {
                window.location.href = '/lv-index/readmore.html?nid=' + nid;
            },

            // 检查登录状态
            checkAuth() {
                if (!this.currentUser.uid) {
                    alert('请先登录！');
                    window.location.href = '/lv-user/reg.html';
                    return false;
                }
                this.openForm();
                return true;
            },

            // 显示表单
            openForm() {
                document.getElementById('postForm').style.display = 'block';
                this.isFormVisible = true;
            },

            // 隐藏表单
            hideForm() {
                document.getElementById('postForm').style.display = 'none';
                this.isFormVisible = false;
                this.newNote = { title: '', content: '', images: [] };

                // 清空文件输入
                for (let i = 1; i <= 3; i++) {
                    const input = this.$refs[`fileInput${i}`]?.[0];
                    if (input) input.value = '';
                }
            },

            // 处理文件上传
            handleFileUpload(index) {
                const fileInput = this.$refs[`fileInput${index + 1}`][0];
                if (fileInput.files.length > 0) {
                    this.newNote.images[index] = fileInput.files[0];
                }
            },

            // 提交新游记
            submitPost() {
                if (!this.currentUser?.uid) {
                    alert('登录状态已失效，请重新登录！');
                    window.location.href = '/lv-user/reg.html';
                    return;
                }

                if (!this.newNote.title.trim()) {
                    alert('请输入标题');
                    return;
                }

                if (this.newNote.content.length < 20) {
                    alert('内容至少需要20字');
                    return;
                }

                const formData = new FormData();
                formData.append('uid', this.currentUser.uid);
                formData.append('title', this.newNote.title);
                formData.append('content', this.newNote.content);

                // 添加图片文件
                let hasImage = false;
                const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
                const MAX_TOTAL_SIZE = 5 * 1024 * 1024; // 5MB
                let totalSize = 0;

                for (let i = 1; i <= 3; i++) {
                    const fileInput = this.$refs[`fileInput${i}`]?.[0];
                    if (fileInput && fileInput.files.length > 0) {
                        const file = fileInput.files[0];
                        if (file.size > MAX_FILE_SIZE) {
                            alert(`图片${i}大小超过限制 (最大2MB)`);
                            return;
                        }
                        totalSize += file.size;
                        formData.append(`img${i}`, file);
                        hasImage = true;
                    }
                }

                if (hasImage && totalSize > MAX_TOTAL_SIZE) {
                    alert(`总图片大小超过限制 (最大5MB)`);
                    return;
                }

                if (!hasImage) {
                    if (!confirm('确定要发布没有图片的游记吗？')) {
                        return;
                    }
                }

                this.isSubmitting = true;

                axios.post('/index/note', formData, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    timeout: 30000
                })
                    .then(response => {
                        this.isSubmitting = false;
                        if (response.data && response.data.code === 1) {
                            alert('发布成功！');
                            this.hideForm();
                            this.fetchUserNotes(); // 刷新列表
                        } else {
                            alert(`发布失败：${response.data ? response.data.msg : '未知错误'}`);
                        }
                    })
                    .catch(error => {
                        console.error('发布失败:', error);
                        let errorMsg = '发布失败';
                        if (error.response) {
                            errorMsg += `: ${error.response.data?.msg || error.response.statusText}`;
                            if (error.response.data?.data) {
                                console.error('错误详情:', error.response.data.data);
                            }
                        } else if (error.request) {
                            errorMsg += ': 无服务器响应';
                        } else {
                            errorMsg += `: ${error.message}`;
                        }
                        alert(errorMsg);
                    });
            }
        }
    });
</script>
</body>
</html>